<!-- 也可以下载示例项目查看使用方法 -->
<template>
    <view>
        <view class="upload-wrap">
            <view class="btn-click mgb-16 upload-btn" @click="handleUploadClick" v-show="!disabled"
                v-if="fileList.length < count">
                <uv-icon name="plus-circle" color="#2979ff" size="56rpx"></uv-icon>
                <text class="upload-text">上传文件</text>
            </view>
            <view class="mgb-16 file-wrap" v-for="(item, index) in fileList" :key="index">
                <view class="btn-click file-line">
                    <!-- <view class="btn-click file-line" @click="handleUploadFile(item)"> -->
                    <view class="file-info" @click="handlePreview(item)">
                        <uv-icon name="folder" color="#2979ff" size="48rpx"></uv-icon>
                        <text class="file-name">{{ item.name || '文件' }}</text>
                    </view>
                    <uv-icon name="close" color="#2979ff" size="48rpx" @click="handleDeleteFile(index)"
                        v-if="!disabled"></uv-icon>
                </view>
            </view>
            <xe-upload ref="XeUpload" @callback="handleUploadCallback"></xe-upload>
        </view>
    </view>
</template>

<script>
// import { mapState } from 'vuex';
export default {
    props: {
        type: {
            default: 'file', // image, video, file
            type: String,
        },
        list: {
            default: () => ([]),
            type: Array,
        },
        disabled: {
            default: false,
            type: Boolean,
        },
        size: {
            default: 5,
            type: Number,
        },
        count: {
            default: 1,
            type: Number,
        },
    },

    // computed: {
    //     ...mapState(['token']),
    // },
    emits: ['update'],
    data() {
        return {
            fileList: [],
            fileType: ['png', 'jpeg', 'jpg', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx']
        };
    },
    watch: {
        list: {
            handler(val) {
                this.fileList = val || [];
            },
            immediate: true,
            deep: true,
        },
    },
    methods: {
        handleUploadClick() {
            // 使用默认配置则不需要传入第二个参数
            // type: ['image', 'video', 'file'];
            // this.$refs.XeUpload.upload('file', {});
            this.$refs.XeUpload.upload(this.type, {
                count: this.count,
                // sizeType: ['original', 'compressed'],
                // sourceType: ['album'],
            });
        },
        handleUploadCallback(e) {
            console.log("e:", e);
            if (e.type === 'warning') {
                uni.showToast({
                    title: '上传失败，请重新上传',
                    icon: 'none'
                })
            }
            if (!['choose', 'success'].includes(e.type)) return;
            const flieArr = e.data[0].name.split('.');
            let suffix = flieArr[flieArr.length - 1];
            console.log("suffix:", suffix);
            if (this.fileType.includes(suffix)) {
                this.handleUploadFile(e.data[0])
            } else {
                uni.showToast({
                    title: `不支持上传${e.data[0].name.split('.').pop()}文件类型`,
                    icon: 'none'
                })
            }
        },
        // 自定义上传
        handleUploadFile(item) {
            //限制上传文件大小 10M
            if (item.size > 1024 * 1024 * this.size) {
                return uni.showToast({
                    title: `文件大小不能超过${this.size}M`,
                    icon: 'none'
                })
            }
            this.fileList.push({
                url: item.tempFilePath,
                name: item.name,
            });
            this.$emit('update', this.fileList);
            // uni.uploadFile({
            //     url: this.api.hostv1 + '/v1/SysFile/CreateWithFile',
            //     filePath: item.tempFilePath,
            //     name: 'file',
            //     formData: {
            //         TypeCode: "YJCP",
            //         FKey: undefined,
            //     },
            //     header: {
            //         Authorization: 'Bearer ' + this.token
            //     },
            //     success: (res) => {
            //         const tmpData = JSON.parse(res.data);
            //         console.log("🚀 ~ handleUploadFile ~ tmpData:", tmpData)
            //         if (tmpData.IsSuccess) {
            //             this.fileList.push({
            //                 url: tmpData.Data.Id,
            //                 name: item.name,
            //                 type: tmpData.Data.FileType
            //             });
            //             this.$emit('update', this.fileList);
            //         }
            //         uni.showToast({ title: tmpData.IsSuccess ? '上传成功' : '上传失败', icon: 'none' });
            //     },
            //     fail: (err) => {
            //         console.log('handleUpload fail', err);
            //         uni.showToast({ title: '出错啦', icon: 'none' });
            //     },
            // });
        },
        // 预览
        handlePreview(item) {
            const fileType = this.getFileType(item.name);
            if (fileType === 'image') {
                return uni.previewImage({
                    current: 0,
                    urls: [item.url],
                });
            }
            // #ifndef H5
            if (fileType === 'office') {
                return uni.openDocument({
                    filePath: item.url,
                    fail: (err) => {
                        console.log(err);
                        uni.showToast({ icon: 'none', title: '文件预览失败' });
                    },
                });
            }
            // #endif
            uni.showModal({
                title: '提示',
                content: item.name,
                showCancel: false,
            });
        },
        /**
         * 获取文件类型
         * @param {String} fileName 文件链接
         * @returns {String} fileType => '', image, video, audio, office, unknown
         */
        getFileType(fileName = '') {
            const flieArr = fileName.split('.');
            let suffix = flieArr[flieArr.length - 1];
            if (!suffix) return '';
            suffix = suffix.toLocaleLowerCase();
            const image = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp'];
            if (image.includes(suffix)) return 'image';
            const video = ['mp4', 'm4v'];
            if (video.includes(suffix)) return 'video';
            const audio = ['mp3', 'm4a', 'wav', 'aac'];
            if (audio.includes(suffix)) return 'audio';
            const office = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'plain'];
            if (office.includes(suffix)) return 'office';
            return 'unknown';
        },
        handleDeleteFile(index) {
            this.fileList.splice(index, 1);
            this.$emit('update', this.fileList);
        },
        reset() {
            this.fileList = []
        }
    },
};
</script>
<style lang="scss" scoped>
view {
    box-sizing: border-box;
}

.btn-click {
    transition: all 0.3s;
    opacity: 1;
}

.btn-click:active {
    opacity: 0.5;
}

.mgb-16 {
    margin-bottom: 16rpx;

    &:last-child {
        margin-bottom: 0;
    }
}

.upload-wrap {
    width: 100%;
    border-radius: 16rpx;
    background: white;
    padding: 32rpx;

    .upload-btn {
        width: 100%;
        height: 176rpx;
        border: 2rpx dashed #AAAAAA;
        background: #FAFAFA;
        border-radius: 16rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;

        .upload-icon {
            width: 48rpx;
            height: 48rpx;
            margin-bottom: 8rpx;
        }

        .upload-text {
            font-size: 26rpx;
            color: #9E9E9E;
            line-height: 40rpx;
        }
    }

    .file-wrap {
        .file-line {
            width: 100%;
            background: #F5F5F5;
            border-radius: 8rpx;
            padding: 16rpx;
            font-size: 26rpx;
            color: #1A1A1A;
            line-height: 40rpx;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .file-info {
                width: 90%;
                display: flex;
                align-items: center;

                .file-name {
                    max-width: 80%;
                    padding-left: 16rpx;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }
            }

            .file-icon {
                width: 40rpx;
                height: 40rpx;
                flex-shrink: 0;
            }

            .file-empty {
                color: #999999;
            }
        }
    }
}
</style>
